import 'package:hrf_app/common/api/user/user.dart';
import 'package:hrf_app/common/models/user/login_token.dart';
import 'package:hrf_app/common/routers/names.dart';
import 'package:hrf_app/common/services/user.dart';
import 'package:hrf_app/common/values/constants.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/route_manager.dart';
import 'package:get/state_manager.dart';

import 'package:dio/dio.dart';

class LoginController extends GetxController {
  final TextEditingController usernameController = TextEditingController(text: "admin");
  final TextEditingController passwordController = TextEditingController(text: "123456");
  bool isPasswordVisible = false;

  _initData() {
    update(["login"]);
  }

  void onSetIp() {
    Get.toNamed(RouteNames.systemHttpIpSet);
  }

  void onSignIn() async {
    String userName = usernameController.text;
    String password = passwordController.text;
    if (Constants.appIpAccount == userName &&
        password == Constants.appIpPassword) {
      usernameController.text = "";
      passwordController.text = "";
      update(["login"]);
      return;
    }

      FormData formData = FormData.fromMap({
        "username": userName,
        'password': password,
      });
      Map<String, dynamic> res = await UserApi.login(formData);
      if (res['code'] == "00000") {
        // 本地保存 token
        LoginToken loginToken = LoginToken.fromJson(res["data"]);
        await UserService.to.setToken(loginToken.accessToken!);
        await UserService.to.getUserInfo();
        Get.offAllNamed(RouteNames.mainTab);
      } else {
        EasyLoading.showError("账号或者密码错误！");
      }
  }

  void togglePasswordVisibility() {
    isPasswordVisible = !isPasswordVisible;
    update(["login"]);
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    super.onClose();
    usernameController.dispose();
    passwordController.dispose();
  }
}
